/**
 * 
 */
package fb.chatter.controller;

import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;

import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressBar;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.FlowPane;
import javafx.stage.Stage;
import javafx.util.Callback;
import fb.chatter.control.cloner.AnchorPaneCloner;
import fb.chatter.control.cloner.ImageViewCloner;
import fb.chatter.control.cloner.TextAreaCloner;
import fb.chatter.model.RequestedFriendsModel;
import fb.chatter.model.User;
import fb.chatter.model.Users;
import fb.chatter.utils.ExceptionUtils;
import fb.chatter.utils.FriendsUtils;

/**
 * @author Horizon
 * 
 */
public class FriendListFormController implements Initializable {

	/**
	 * Define JavaFX2.0 components
	 */
	@FXML
	private AnchorPane rootPane;
	@FXML
	private ProgressBar prbLoadingPhotosPercent;
	@FXML
	private Label lbLoadingPhotosPercent;
	@FXML
	private FlowPane flpfriends;
	@FXML
	private TextField txtSearch;
	@FXML
	private Button btnSearch;
	@FXML
	private AnchorPane acpFriend;

	@Override
	public void initialize(URL location, ResourceBundle resources) {

		// Create Scene
		Scene scene = new Scene(rootPane, 900, 500);

		// Create stage
		Stage stage = new Stage();
		stage.getIcons().add(new Image("/logo-friends.png"));
		stage.setTitle("Facebook friends");
		stage.setScene(scene);
		stage.centerOnScreen();
		stage.show();
		
		final Users originalFriends = RequestedFriendsModel.getInstance().getFriends();
		
		txtSearch.textProperty().addListener(new ChangeListener<String>() {

			@Override
			public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {

				System.out.println(newValue);
				Users searchedFriends = FriendsUtils.searchByFriendName(originalFriends, newValue);
				
				// First, don't allow user enter the search value
				txtSearch.setEditable(false);
				
				// Then, update UI 
				updateUIBySearchedFriends(searchedFriends);
				
				// Finally, allow user enter the search value
				txtSearch.setEditable(true);
			}
		});
	}
	
	
	
	/**
	 * To update UI when the searched result changed
	 * @param searchedfriends
	 */
	private void updateUIBySearchedFriends(Users searchedfriends){
		
		AnchorPaneCloner anchorPaneCloner = new AnchorPaneCloner();
		AnchorPane backupFriendPane = anchorPaneCloner.clone(acpFriend, "abc");
		
		// Clone a textArea for backup
		TextAreaCloner textAreaCloner = new TextAreaCloner();
		TextArea backupFriendTextArea = textAreaCloner.clone((TextArea) acpFriend.getChildren().get(0), "abcd");
		
		// Clone a imageView for backup
		ImageViewCloner imageViewCloner = new ImageViewCloner();
		ImageView backupFriendImageView= imageViewCloner.clone((ImageView) acpFriend.getChildren().get(1), "abcde");			
		
		flpfriends.getChildren().clear();
		for (int i = 0; i < searchedfriends.getData().size(); i++) {
			
			User f = searchedfriends.getData().get(i);
			
			// Clone a textArea with the backup textArea
			TextArea txa = textAreaCloner.clone(backupFriendTextArea, "txa" + f.getId());
			txa.setText(f.getName());
			
			// Clone a imageView with the backup imageView
			ImageView imv = imageViewCloner.clone(backupFriendImageView, "imv" + f.getId());
			imv.setImage(f.getPicture());
			
			// Add the cloned textArea and cloned imageView to UI
			AnchorPane acp = anchorPaneCloner.clone(backupFriendPane, "acp" + f.getId());
			acp.getChildren().clear();
			acp.getChildren().add(txa);
			acp.getChildren().add(imv);
			
			flpfriends.getChildren().add(acp);
		}
	}
	
	/**
	 * To process when user double click on a textArea or an imageView
	 * @param e
	 */
	@FXML
	public void handleMouseClicked(MouseEvent event){
		
		// Double click
		if(event.getClickCount() == 2){
			
			String friendId = null;
			if(event.getSource() instanceof TextArea){
				friendId = ((TextArea) event.getSource()).getId().substring(3);
			}
			if(event.getSource() instanceof ImageView){
				friendId = ((ImageView) event.getSource()).getId().substring(3);
			}
			
			// Now, We are sure about that friendId != null  
			final User friend = FriendsUtils.searchByFriendId(RequestedFriendsModel.getInstance().getFriends(), friendId); 
			try {
				FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("../view/ChattingForm.fxml"));
				fxmlLoader.setControllerFactory(new Callback<Class<?>, Object>() {
					
					@Override
					public Object call(Class<?> arg0) {
						if(arg0.equals(ChattingFormController.class)){
							return new ChattingFormController(friend);
						}
						return null;
					}
				});
				
				fxmlLoader.load();
				
			} catch (IOException e) {
				ExceptionUtils.log(e);
			}
		}
	}
}
